package com.baimawangzi.recovery.util.dbutil;

import com.baimawangzi.recovery.util.propertiesutil.PropertiesUtil;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * 封装JDBC的连接操作
 */
public class DBConnection {
    private static final String URL_AGGREMENT="jdbc:mysql://";

    private static String url;

    private static String username;
    private static String password;

    //通过使用静态游离块来加载外部文件资源jdbc.properties
    static {
        try {
            PropertiesUtil p = new PropertiesUtil("/jdbc.properties");
            String driver = p.getProperties("driver");
            String ip = p.getProperties("ip");
            String port = p.getProperties("port");
            String dbname = p.getProperties("dbname");
            String url_parameter=p.getProperties("url_parameter");
            url=URL_AGGREMENT+ ip +":"+ port +"/"+ dbname +url_parameter;
            username = p.getProperties("username");
            password = p.getProperties("password");
            //5.加载数据库驱动
            Class.forName(driver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static Connection conn;

    //获取连接对象
    public static Connection getConn(){
        if(conn == null){
            //使用DriverManager类来获取连接
            try {
                conn = DriverManager.getConnection(url, username, password);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return conn;
    }

    //关闭数据库连接资源
    public static void close( Connection conn){
        if(conn != null){
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}
